package com.app.conrtoller;

import com.alibaba.fastjson.JSON;
import com.app.domain.ExternalResponse;
import com.app.domain.UploadParameter;
import com.app.domain.YjData;
import com.app.domain.wxjjlb.CompressSlurry;
import com.app.domain.wxjjlb.CompressSlurryResult;
import com.app.service.UploadParameterService;
import com.app.service.UploadService;
import com.app.service.YjDataService;
import com.app.service.algs.WxjjlbService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/wxjjlb")
public class WxjjlbController {
    @Value("${yj.wxjjlb.serverHost}")
    private String serverHost;
    @Value("${yj.wxjjlb.appKey}")
    private String appKey;
    @Value("${yj.wxjjlb.appSecret}")
    private String appSecret;
    @Autowired
    YjDataService yjDataService;
    @Autowired
    UploadParameterService uploadParameterService;
    @Autowired
    UploadService uploadService;
    @Autowired
    WxjjlbService wxjjlbService;


    @RequestMapping("/upload")
    @ResponseBody
    public ExternalResponse upload(@RequestParam(value = "ids[]") String[] ids) throws InterruptedException, NoSuchAlgorithmException {
        ExternalResponse externalResponse = null;
        int total = ids.length;
        int succTotal = 0;
        int failTotal = 0;
        StringBuffer responseContent = new StringBuffer();
        responseContent.append("本次共上传数据：【" + total + "】条,");
        List<YjData> yjDataList = yjDataService.findList(ids);
        List<List<YjData>> groupList = new ArrayList<>();
        yjDataList.stream().collect(Collectors.groupingBy(YjData::getBridge_code, Collectors.toList())).forEach((bridge_code, yjDataGroupList) -> {
            groupList.add(yjDataGroupList);
        });
        UploadParameter uploadParameter = uploadParameterService.findOne("25");
        for (List<YjData> yjData : groupList) {
            List<Integer> userIds = yjData.stream().map(o -> o.getId()).collect(Collectors.toList());
            Map<String, Object> map = yjDataService.findDate(userIds);
            CompressSlurry compressSlurry = null;
            try {
                compressSlurry = wxjjlbService.getYjdata(yjDataList, uploadParameter, appKey, appSecret, map);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String s = JSON.toJSONString(compressSlurry);
            CompressSlurryResult compressSlurryResult = uploadService.sendMessage(serverHost, s);
           if ("0".equals(compressSlurryResult.getCode()) ){
               for (Integer userId : userIds) {
                   updateState("1", String.valueOf(userId));
                   succTotal++;
               }
           }else {
               for (Integer userId : userIds) {
                   updateState("0", String.valueOf(userId));
                   failTotal++;
               }
           }
        }
        responseContent.append("成功【" + succTotal + "】条,失败" + failTotal + "条");
        externalResponse = new ExternalResponse(0, responseContent.toString(), "");
        return externalResponse;
    }

    private void updateState(String state, String id) {
        yjDataService.updateById(state, id);
    }
}
